<template>
  <div class="home-container" :class="getBackgroundClass()" :style="getBackgroundStyle()">
    <!-- 时间显示 -->
    <div class="time-section">
      <div class="current-time">{{ currentTime }}</div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-container">
        <div class="search-input-wrapper">
          <div class="search-engine-indicator">
            <img :src="getCurrentEngineLogo" :alt="getCurrentEngineLabel" class="engine-logo" />
            <span class="engine-label">{{ getCurrentEngineLabel }}</span>
          </div>
          <input v-model="searchQuery" @input="handleSearchInput" @keydown="handleKeyDown"
            @keydown.tab.prevent="switchEngine" @focus="showSuggestions = true" @blur="hideSuggestions" type="text"
            class="search-input" placeholder="搜索..." autocomplete="off" />


        </div>

        <!-- 搜索建议 -->
        <div v-if="showSuggestions && suggestions.length > 0" class="suggestions-dropdown">
          <div v-for="(suggestion, index) in suggestions" :key="index" @mousedown="selectSuggestion(suggestion)"
            @mouseenter="selectedSuggestionIndex = index"
            :class="['suggestion-item', { 'selected': selectedSuggestionIndex === index }]">
            {{ suggestion }}
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="isLoadingSuggestions" class="loading-indicator">
          <div class="loading-spinner"></div>
        </div>
      </div>
    </div>

    <!-- 书签区域 -->
    <div v-if="bookmarks.length > 0" class="bookmarks-section">
      <div class="bookmarks-grid">
        <a v-for="bookmark in bookmarks" :key="bookmark.id" :href="bookmark.url" target="_blank" class="bookmark-item">
          <div class="bookmark-icon">
            <img :src="bookmark.iconUrl || getFavicon(bookmark.url)" :alt="bookmark.title" @error="handleIconError" />
          </div>
          <span class="bookmark-title">{{ bookmark.title }}</span>
        </a>
      </div>
    </div>

    <!-- 设置按钮 -->
    <router-link to="/settings" class="settings-button">
      ⚙️
    </router-link>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useBookmarksStore } from '@/stores/bookmarks'

interface SearchEngine {
  label: string
  value: string
  searchUrl: string
  logo?: string
}

// 搜索相关
const searchQuery = ref('')
const selectedEngine = ref('bing')
const suggestions = ref<string[]>([])
const showSuggestions = ref(false)
const isLoadingSuggestions = ref(false)
const selectedSuggestionIndex = ref(-1) // 当前选中的建议索引，-1表示没有选中

// 初始化stores
const authStore = useAuthStore()
const bookmarksStore = useBookmarksStore()

const searchEngines: SearchEngine[] = [
  { label: 'Google', value: 'google', searchUrl: 'https://www.google.com/search?q=', logo: 'https://ts1.tc.mm.bing.net/th/id/ODF.cQGDzDdW-31GYqwCeCzTrw?w=32&h=32&qlt=90&pcl=fffffa&o=6&pid=1.2' },
  { label: '百度', value: 'baidu', searchUrl: 'https://www.baidu.com/s?wd=', logo: 'https://www.baidu.com/favicon.ico' },
  { label: '必应', value: 'bing', searchUrl: 'https://www.bing.com/search?q=', logo: 'https://ts4.tc.mm.bing.net/th/id/ODLS.a3097c96-5ad2-4065-96c9-624226a1320f?w=32&h=32&qlt=90&pcl=fffffa&o=6&pid=1.2' }
]

// 使用store中的书签数据
const bookmarks = computed(() => bookmarksStore.sortedBookmarks)

// 初始化用户设置
const initializeUserSettings = () => {
  if (authStore.user && authStore.settings) {
    selectedEngine.value = authStore.settings.searchEngine?.toLowerCase() || 'google'
  }
}

// 监听用户设置变化
watch(() => authStore.settings, (newSettings) => {
  if (newSettings) {
    selectedEngine.value = newSettings.searchEngine?.toLowerCase() || 'google'
  }
}, { deep: true })

// 获取背景样式class
const getBackgroundClass = () => {
  if (!authStore.settings) return ''

  const bgType = authStore.settings.backgroundType?.toLowerCase()
  switch (bgType) {
    case 'gradient':
      return 'gradient-bg'
    case 'image':
      return 'image-bg'
    case 'color':
      return 'color-bg'
    default:
      return ''
  }
}

// 获取背景样式对象
const getBackgroundStyle = () => {
  if (!authStore.settings) return {}

  const bgType = authStore.settings.backgroundType?.toLowerCase()
  const bgValue = authStore.settings.backgroundValue

  switch (bgType) {
    case 'image':
      return bgValue ? { backgroundImage: `url(${bgValue})` } : {}
    case 'color':
      return bgValue ? { backgroundColor: bgValue } : {}
    default:
      return {}
  }
}

// 搜索功能
const handleSearch = () => {
  if (!searchQuery.value.trim()) return

  const engine = searchEngines.find(e => e.value === selectedEngine.value)
  if (engine) {
    const searchUrl = engine.searchUrl + encodeURIComponent(searchQuery.value)
    window.open(searchUrl, '_blank')
  }
}

// 切换搜索引擎
const switchEngine = () => {
  const currentIndex = searchEngines.findIndex(e => e.value === selectedEngine.value)
  const nextIndex = (currentIndex + 1) % searchEngines.length
  selectedEngine.value = searchEngines[nextIndex].value
}

// 获取当前搜索引擎信息
const getCurrentEngineLabel = computed(() => {
  const engine = searchEngines.find(e => e.value === selectedEngine.value)
  return engine?.label || 'Google'
})

const getCurrentEngineLogo = computed(() => {
  const engine = searchEngines.find(e => e.value === selectedEngine.value)
  return engine?.logo || 'https://ts1.tc.mm.bing.net/th/id/ODF.cQGDzDdW-31GYqwCeCzTrw?w=32&h=32&qlt=90&pcl=fffffa&o=6&pid=1.2'
})

// 搜索建议缓存
const suggestionCache = new Map<string, { suggestions: string[], timestamp: number }>()
const CACHE_DURATION = 5 * 60 * 1000 // 5分钟

// 优化后的搜索建议获取
const fetchSuggestions = async (query: string) => {
  if (!query.trim()) {
    suggestions.value = []
    return
  }

  // 检查缓存
  const cached = suggestionCache.get(query.toLowerCase())
  if (cached && Date.now() - cached.timestamp < CACHE_DURATION) {
    suggestions.value = cached.suggestions
    return
  }

  isLoadingSuggestions.value = true

  try {
    // 优化1: 直接使用JSONP，避免代理服务的额外延迟
    await fetchSuggestionsJSONP(query)
  } catch (error) {
    console.warn('获取搜索建议失败:', error)
    suggestions.value = []
  } finally {
    isLoadingSuggestions.value = false
  }
}

// JSONP备用方案
const fetchSuggestionsJSONP = (query: string): Promise<void> => {
  return new Promise((resolve) => {
    const script = document.createElement('script')
    const callbackName = `jsonp_callback_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

      // 设置全局回调函数
      ; (window as any)[callbackName] = (data: any) => {
        try {
          if (Array.isArray(data) && data.length > 1 && Array.isArray(data[1])) {
            const newSuggestions = data[1].slice(0, 8)
            suggestions.value = newSuggestions

            // 缓存结果
            suggestionCache.set(query.toLowerCase(), {
              suggestions: newSuggestions,
              timestamp: Date.now()
            })
          }
        } catch (error) {
          console.warn('JSONP解析失败:', error)
          suggestions.value = []
        } finally {
          // 清理
          document.head.removeChild(script)
          delete (window as any)[callbackName]
          resolve()
        }
      }

    script.src = `https://api.bing.com/osjson.aspx?query=${encodeURIComponent(query)}&JsonType=callback&JsonCallback=${callbackName}`
    script.onerror = () => {
      console.warn('JSONP请求失败')
      suggestions.value = []
      document.head.removeChild(script)
      delete (window as any)[callbackName]
      resolve()
    }

    // 设置超时
    setTimeout(() => {
      if (document.head.contains(script)) {
        document.head.removeChild(script)
        delete (window as any)[callbackName]
        suggestions.value = []
        resolve()
      }
    }, 800)

    document.head.appendChild(script)
  })
}

// 优化2: 增加防抖延迟，减少API调用频率
let searchTimeout: NodeJS.Timeout
const handleSearchInput = () => {
  clearTimeout(searchTimeout)
  selectedSuggestionIndex.value = -1 // 重置选中索引
  
  // 如果输入为空，立即清空建议
  if (!searchQuery.value.trim()) {
    suggestions.value = []
    return
  }
  
  // 增加防抖延迟到300ms，减少频繁请求
  searchTimeout = setTimeout(() => {
    fetchSuggestions(searchQuery.value)
  }, 300)
}

// 键盘事件处理
const handleKeyDown = (event: KeyboardEvent) => {
  if (!showSuggestions.value || suggestions.value.length === 0) {
    // 如果没有建议显示，只处理回车键
    if (event.key === 'Enter') {
      handleSearch()
    }
    return
  }

  switch (event.key) {
    case 'ArrowDown':
      event.preventDefault()
      selectedSuggestionIndex.value = selectedSuggestionIndex.value < suggestions.value.length - 1
        ? selectedSuggestionIndex.value + 1
        : 0
      break

    case 'ArrowUp':
      event.preventDefault()
      selectedSuggestionIndex.value = selectedSuggestionIndex.value > 0
        ? selectedSuggestionIndex.value - 1
        : suggestions.value.length - 1
      break

    case 'Enter':
      event.preventDefault()
      if (selectedSuggestionIndex.value >= 0 && selectedSuggestionIndex.value < suggestions.value.length) {
        // 选择当前高亮的建议
        selectSuggestion(suggestions.value[selectedSuggestionIndex.value])
      } else {
        // 直接搜索当前输入的内容
        handleSearch()
      }
      break

    case 'Escape':
      event.preventDefault()
      showSuggestions.value = false
      selectedSuggestionIndex.value = -1
      break
  }
}

// 选择搜索建议
const selectSuggestion = (suggestion: string) => {
  searchQuery.value = suggestion
  showSuggestions.value = false
  selectedSuggestionIndex.value = -1
  handleSearch()
}

// 隐藏搜索建议
const hideSuggestions = () => {
  setTimeout(() => {
    showSuggestions.value = false
    selectedSuggestionIndex.value = -1
  }, 200)
}

// 时间相关
const currentTime = ref('')
const currentDate = ref('')
let timeInterval: NodeJS.Timeout

const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleTimeString('zh-CN', {
    hour12: false,
    hour: '2-digit',
    minute: '2-digit'
  })
  currentDate.value = now.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
}

// 书签相关
const getFavicon = (url: string) => {
  try {
    const domain = new URL(url).hostname
    return `https://www.google.com/s2/favicons?domain=${domain}&sz=32`
  } catch {
    return 'https://myicons.yuholy.site/configData/icon/5_TV/Cover.png'
  }
}

const handleIconError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = 'https://myicons.yuholy.site/configData/icon/5_TV/Cover.png'
}

// 生命周期
onMounted(async () => {
  updateTime()
  timeInterval = setInterval(updateTime, 1000)

  // 如果用户已登录，获取书签数据和用户设置
  if (authStore.user) {
    await bookmarksStore.fetchBookmarks()
    await authStore.fetchUserSettings()
    initializeUserSettings()
  }
})

onUnmounted(() => {
  if (timeInterval) {
    clearInterval(timeInterval)
  }
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
})
</script>

<style scoped lang="scss">
.home-container {
  min-height: 100vh;
  background: #000000;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  position: relative;

  [data-theme="dark"] & {
    background: #000000;
  }
}

/* 动态背景样式 */
.home-container.gradient-bg {
  background: linear-gradient(135deg, #1e1e1e 0%, #2a2a2a 50%, #1a1a1a 100%);
}

.home-container.image-bg {
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
}

.home-container.color-bg {
  /* 背景颜色通过内联样式设置 */
}

.time-section {
  text-align: center;
  margin-top: 5rem;
  margin-bottom: 1.5rem;
  color: #ffffff;
}

.current-time {
  font-size: 3rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;

  @media (max-width: 768px) {
    font-size: 3rem;
  }
}

.current-date {
  font-size: 1.2rem;
  opacity: 0.8;
  font-weight: 400;
}

.search-section {
  width: 100%;
  max-width: 600px;
  text-align: center;
  margin-bottom: 3rem;
}

.search-container {
  position: relative;
}

.search-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  padding: 0.2rem 1.2rem;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;

  &:focus-within {
    background: rgba(255, 255, 255, 0.15);
    border-color: rgba(255, 255, 255, 0.3);
    box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1);
  }
}

.search-input {
  flex: 1;
  background: transparent;
  border: none;
  outline: none;
  color: #ffffff;
  font-size: 1rem;
  padding: 0.3rem 0;

  &::placeholder {
    color: rgba(255, 255, 255, 0.6);
  }
}

.search-engine-indicator {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-left: -1rem;

  padding: 0.25rem 0.75rem;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 20px;
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.8);
  transform: scale(0.8);
}

.engine-logo {
  width: 16px;
  height: 16px;
  border-radius: 2px;
}

.search-button {
  background: transparent;
  border: none;
  color: rgba(255, 255, 255, 0.8);
  cursor: pointer;
  padding: 0.5rem;
  border-radius: 50%;
  transition: all 0.3s ease;

  &:hover {
    color: #ffffff;
    background: rgba(255, 255, 255, 0.1);
  }
}

.suggestions-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  margin-top: 0.5rem;
  backdrop-filter: blur(10px);
  z-index: 1000;
  overflow: hidden;
}

.suggestion-item {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem 1rem;
  color: rgba(255, 255, 255, 0.8);
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover,
  &.selected {
    background: rgba(255, 255, 255, 0.15);
    color: #ffffff;
  }

  &.selected {
    background: rgba(64, 158, 255, 0.2);
    border-left: 3px solid #409eff;
  }

  &:not(:last-child) {
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  }
}

.suggestion-icon {
  opacity: 0.6;
  flex-shrink: 0;
}

.loading-indicator {
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  margin-top: 1rem;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid #ffffff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.bookmarks-section {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  margin-bottom: 2rem;
}

.bookmarks-grid {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  gap: 1.2rem;
  padding: 0 1rem;

  @media (max-width: 768px) {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 1rem;
  }
}

.bookmark-item {
  display: flex;
  align-items: center;
  padding: 0.2rem 0.75rem;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  text-decoration: none;
  color: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  gap: 5px;
  &:hover {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(255, 255, 255, 0.2);
    color: #ffffff;
    transform: translateY(-2px);
  }
}

.bookmark-icon {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;

  img {
    width: 32px;
    height: 32px;
    object-fit: cover;
    transform: scale(0.7);
  }
}

.bookmark-title {
  font-size: 0.9rem;
  text-align: center;
  line-height: 1.3;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.settings-button {
  position: fixed;
  top: 2rem;
  right: 2rem;
  width: 12px;
  height: 12px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: rgba(255, 255, 255, 0.8);
  text-decoration: none;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  opacity: 0.5;

  &:hover {
    background: rgba(255, 255, 255, 0.15);
    border-color: rgba(255, 255, 255, 0.3);
    color: #ffffff;
    transform: rotate(90deg);
    opacity: 1;
  }

  @media (max-width: 768px) {
    top: 1rem;
    right: 1rem;
    width: 44px;
    height: 44px;
  }
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
}

::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}
</style>